package com.sugar.queryinfo.module.business.service.dataquery;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sugar.queryinfo.framework.common.exception.ServiceException;
import com.sugar.queryinfo.framework.security.core.util.SecurityFrameworkUtils;
import com.sugar.queryinfo.module.business.api.bi.BackInvestApi;
import com.sugar.queryinfo.module.business.api.bi.dto.req.common.UserThreeInfoReqVO;
import com.sugar.queryinfo.module.business.api.bi.dto.req.common.ZCI101ReqVO;
import com.sugar.queryinfo.module.business.api.bi.dto.req.sjzwsj.ZCI003ReqVO;
import com.sugar.queryinfo.module.business.api.bi.dto.resp.*;
import com.sugar.queryinfo.module.business.controller.admin.dataquery.vo.audit.DataQueryAuditSimpleRespVO;
import com.sugar.queryinfo.module.business.controller.admin.dataquery.vo.audit.DataQuerySaveAuditRespVO;
import com.sugar.queryinfo.module.business.controller.admin.userextend.vo.UserExtendSaveReqVO;
import com.sugar.queryinfo.module.business.dal.dataobject.apitypeinfo.ApiTypeInfoDO;
import com.sugar.queryinfo.module.business.dal.dataobject.config.BizConfigDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataquerydtjd.DataQueryDtjdDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataqueryfqz.DataQueryFqzDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataqueryfyxq.DataQueryFyxqDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataquerylsbg.DataQueryLsbgDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataqueryqjda.DataQueryQjdaDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataqueryqjld.DataQueryQjldDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataquerytanzc.DataQueryTanzcDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataquerywdgz.DataQueryWdgzDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataqueryxfhx.DataQueryXfhxDO;
import com.sugar.queryinfo.module.business.dal.dataobject.dataqueryzwsc.DataQueryZwscDO;
import com.sugar.queryinfo.module.business.dal.dataobject.tffinance.TfFinanceDO;
import com.sugar.queryinfo.module.business.dal.mysql.dataquerydtjd.DataQueryDtjdMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataqueryfqz.DataQueryFqzMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataqueryfyxq.DataQueryFyxqMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataquerylsbg.DataQueryLsbgMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataqueryqjda.DataQueryQjdaMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataqueryqjld.DataQueryQjldMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataquerytanzc.DataQueryTanzcMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataquerywdgz.DataQueryWdgzMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataqueryxfhx.DataQueryXfhxMapper;
import com.sugar.queryinfo.module.business.dal.mysql.dataqueryzwsc.DataQueryZwscMapper;
import com.sugar.queryinfo.module.business.dal.mysql.tffinance.TfFinanceMapper;
import com.sugar.queryinfo.module.business.enums.apitype.ApiTypeEnums;
import com.sugar.queryinfo.module.business.service.apitypeinfo.ApiTypeInfoService;
import com.sugar.queryinfo.module.business.service.config.BizConfigService;
import com.sugar.queryinfo.module.business.service.userextend.UserExtendService;
import com.sugar.queryinfo.module.business.util.HideUtil;
import com.sugar.queryinfo.module.business.util.ObjConvertUtil;
import com.sugar.queryinfo.module.business.util.SqBookUtil;
import com.sugar.queryinfo.module.infra.api.file.FileApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import com.sugar.queryinfo.module.business.controller.admin.dataquery.vo.*;
import com.sugar.queryinfo.module.business.dal.dataobject.dataquery.DataQueryDO;
import com.sugar.queryinfo.framework.common.pojo.PageResult;
import com.sugar.queryinfo.framework.common.util.object.BeanUtils;

import com.sugar.queryinfo.module.business.dal.mysql.dataquery.DataQueryMapper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.sugar.queryinfo.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.queryinfo.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.queryinfo.module.business.enums.ErrorCodeConstants.*;
import static com.sugar.queryinfo.module.business.enums.apitype.ApiTypeEnums.*;

/**
 * 数据查询 Service 实现类
 *
 * @author Ysugar
 */
@Slf4j
@Service
@Validated
public class DataQueryServiceImpl implements DataQueryService {

    @Resource
    private DataQueryMapper dataQueryMapper;
    @Resource
    private TfFinanceMapper tfFinanceMapper;

    @Resource
    private DataQueryTanzcMapper tanzcMapper;
    @Resource
    private DataQueryQjldMapper qjldMapper;
    @Resource
    private DataQueryQjdaMapper qjdaMapper;
    @Resource
    private DataQueryFyxqMapper fyxqMapper;
    @Resource
    private DataQueryZwscMapper zwscMapper;
    @Resource
    private DataQueryLsbgMapper lsbgMapper;
    @Resource
    private DataQueryWdgzMapper wdgzMapper;
    @Resource
    private DataQueryFqzMapper fqzMapper;
    @Resource
    private DataQueryXfhxMapper xfhxMapper;
    @Resource
    private DataQueryDtjdMapper dtjdMapper;

    @Resource
    private ApiTypeInfoService apiTypeInfoService;
    @Resource
    private BackInvestApi backInvestApi;
    @Resource
    private UserExtendService userExtendService;
    @Resource
    private BizConfigService bizConfigService;

    @Resource
    private FileApi fileApi;

    @Override
    public Object refreshData(DataQueryRefreshReqVO reqVO) {
        String type = reqVO.getType();
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        Long deptId = SecurityFrameworkUtils.getLoginUserDeptId();

        UserThreeInfoReqVO userThreeInfoReqVO = new UserThreeInfoReqVO();

        List<String> queryType = null;
        // 获取数据
        if (reqVO.getDataId() != null){
            DataQueryDO dataQueryDO = dataQueryMapper.selectById(reqVO.getDataId());
            if (dataQueryDO == null)
                throw exception(DATA_QUERY_NOT_EXISTS);

            queryType = dataQueryDO.getQueryType();

            userThreeInfoReqVO.setPhone(dataQueryDO.getQueryMobile())
                    .setName(dataQueryDO.getQueryName())
                    .setIdCard(dataQueryDO.getQueryIdCard());
        }else {
            userThreeInfoReqVO.setPhone(reqVO.getQueryMobile()).setName(reqVO.getQueryName())
                    .setIdCard(reqVO.getQueryIdCard());
        }

        // 判断手机号是否为空
        if (StrUtil.isBlank(userThreeInfoReqVO.getPhone())){
            BizConfigDO bizConfig = bizConfigService.getBizConfig(1L);
            if (bizConfig != null){
                userThreeInfoReqVO.setPhone(bizConfig.getValue());
            }
        }

        if (type.equals(TYPE_TZ_C.getApiEnum().getApiKey())) {
            // 扣除 探针C的费用
            getApiPriceAndDeduction(TYPE_TZ_C, userId, deptId);

            try {
                DataQueryTanzcDO dataQueryTanzcDO = queryTzc(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_TZ_C));
                return dataQueryTanzcDO;
            }catch (Throwable e){
                log.error("生成【探针C】报告失败：", e);
                // 退回 探针C的费用
                deductionFeeReturn(TYPE_TZ_C, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_QJLD_V4.getApiEnum().getApiKey())) {
            // 扣除 全景雷达的费用
            getApiPriceAndDeduction(TYPE_QJLD_V4, userId, deptId);

            try {
                DataQueryQjldDO dataQueryQjldDO = queryQjld(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_QJLD_V4));
                return dataQueryQjldDO;
            }catch (Throwable e){
                log.error("生成【全景雷达】报告失败：", e);
                // 退回 探针C的费用
                deductionFeeReturn(TYPE_QJLD_V4, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_QJ_DAN.getApiEnum().getApiKey())) {
            // 扣除 全景档案的费用
            getApiPriceAndDeduction(TYPE_QJ_DAN, userId, deptId);

            try {
                DataQueryQjdaDO dataQueryQjdaDO = queryQjda(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_QJ_DAN));
                return dataQueryQjdaDO;
            }catch (Throwable e){
                log.error("生成【全景档案】报告失败：", e);
                // 退回 探针C的费用
                deductionFeeReturn(TYPE_QJ_DAN, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_FYFX.getApiEnum().getApiKey())) {
            // 扣除 法院风险的费用
            getApiPriceAndDeduction(TYPE_FYFX, userId, deptId);

            try {
                DataQueryFyxqDO dataQueryFyxqDO = queryFyfx(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_FYFX));
                return dataQueryFyxqDO;
            }catch (Throwable e){
                log.error("生成【法院风险】报告失败：", e);
                // 退回 探针C的费用
                deductionFeeReturn(TYPE_FYFX, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_ZWSC.getApiEnum().getApiKey())) {
            // 扣除 在网时长的费用
            getApiPriceAndDeduction(TYPE_ZWSC, userId, deptId);

            try {
                DataQueryZwscDO dataQueryZwscDO = queryZwsc(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_ZWSC));
                return dataQueryZwscDO;
            }catch (Throwable e){
                log.error("生成【在网时长】报告失败：", e);
                // 退回 在网时长的费用
                deductionFeeReturn(TYPE_ZWSC, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_LSBG.getApiEnum().getApiKey())) {
            // 扣除 流水报告的费用
            getApiPriceAndDeduction(TYPE_LSBG, userId, deptId);

            try {
                DataQueryLsbgDO dataQueryLsbgDO = queryLsbg(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_LSBG));
                return dataQueryLsbgDO;
            }catch (ServiceException e){
                // 退回 流水报告的费用
                deductionFeeReturn(TYPE_LSBG, userId, deptId);

                throw e;
            }catch (Throwable e){
                log.error("生成【流水报告】报告失败：", e);
                // 退回 流水报告的费用
                deductionFeeReturn(TYPE_LSBG, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_WDGZ.getApiEnum().getApiKey())) {
            // 扣除 司法报告的费用
            getApiPriceAndDeduction(TYPE_WDGZ, userId, deptId);

            try {
                DataQueryWdgzDO respVO = queryWdgz(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_WDGZ));
                return respVO;
            }catch (Throwable e){
                log.error("生成【司法报告】报告失败：", e);
                // 退回 司法报告的费用
                deductionFeeReturn(TYPE_WDGZ, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_FQZ.getApiEnum().getApiKey())) {
            // 扣除 逾期探查报告的费用
            getApiPriceAndDeduction(TYPE_FQZ, userId, deptId);

            try {
                DataQueryFqzDO respVO = queryFqz(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_FQZ));
                return respVO;
            }catch (Throwable e){
                log.error("生成【逾期探查报告】报告失败：", e);
                // 退回 逾期探查报告的费用
                deductionFeeReturn(TYPE_FQZ, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_XFHX.getApiEnum().getApiKey())) {
            // 扣除 智查全景报告的费用
            getApiPriceAndDeduction(TYPE_XFHX, userId, deptId);

            try {
                DataQueryXfhxDO respVO = queryXfhx(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_XFHX));
                return respVO;
            }catch (Throwable e){
                log.error("生成【智查全景报告】报告失败：", e);
                // 退回 智查全景报告的费用
                deductionFeeReturn(TYPE_XFHX, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else if (type.equals(TYPE_DTJD.getApiEnum().getApiKey())) {
            // 扣除 TC报告的费用
            getApiPriceAndDeduction(TYPE_DTJD, userId, deptId);

            try {
                DataQueryDtjdDO respVO = queryDtjd(userThreeInfoReqVO, userId, deptId, reqVO.getDataId());
                // 更新报告类型
                updateQueryType(reqVO.getDataId(), queryType, Collections.singletonList(TYPE_DTJD));
                return respVO;
            }catch (Throwable e){
                log.error("生成【TC报告】报告失败：", e);
                // 退回 TC报告的费用
                deductionFeeReturn(TYPE_DTJD, userId, deptId);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        } else
            throw exception(DATA_QUERY_TYPE_ERROR);
    }

    private void updateQueryType(Long id, List<String> oldTypes, List<ApiTypeEnums> typeEnums){
        if (oldTypes != null && id != null){
            for (ApiTypeEnums typeEnum : typeEnums) {
                oldTypes.add(typeEnum.getApiEnum().getApiKey());
            }

            DataQueryDO dataQueryDO = new DataQueryDO();
            dataQueryDO.setId(id).setQueryType(oldTypes.stream().distinct().collect(Collectors.toList()));
            dataQueryMapper.updateById(dataQueryDO);
        }
    }

    @Override
    public Long createDataQuery(DataQuerySaveReqVO createReqVO, Long userId, Long deptId) {
        Integer validMethod = createReqVO.getValidMethod();
        String queryName = createReqVO.getQueryName();
        String queryIdCard = createReqVO.getQueryIdCard();
        String queryMobile = createReqVO.getQueryMobile();
        List<String> queryTypes = createReqVO.getQueryType();

        UserThreeInfoReqVO reqVO = new UserThreeInfoReqVO();
        reqVO.setPhone(queryMobile).setName(queryName).setIdCard(queryIdCard);

        // 判断校验方式，插入查询数据
        DataQueryDO dataQueryDO = new DataQueryDO();
        dataQueryDO.setUserId(userId).setDeptId(deptId)
                .setQueryName(queryName).setQueryIdCard(queryIdCard).setQueryMobile(queryMobile)
                .setValidMethod(validMethod)
                .setVaildResult(validMethod).setQueryTime(LocalDateTime.now());
        if (validMethod.equals(0)){
            dataQueryDO.setQueryType(Collections.emptyList()).setVaildResult(0);
        }else {
            ApiTypeEnums apiTypeEnums = validMethod.equals(1) ? TYPE_SF_2E_AUTH : TYPE_SF_3E_AUTH;
            // 扣除 二/三要素校验费用
            getApiPriceAndDeduction(apiTypeEnums, userId, deptId);

            try {
                // 调用二要素接口查询二要素信息
                UserThreeInfoReqVO newReqVO = new UserThreeInfoReqVO();
                newReqVO.setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());
                ZCI001RespVO auth2Resp = backInvestApi.authTwoE(newReqVO);

                dataQueryDO.setVaildResult("0".equals(auth2Resp.getFinal_auth_result()) ? 1 : 2)
                        .setValidBirthday(auth2Resp.getBirthday())
                        .setValidAddress(auth2Resp.getAddress())
                        //.setValidAddressType()
                        .setValidConstellation(auth2Resp.getConstellation())
                        .setValidGender(auth2Resp.getGender())
                        .setValidAge(auth2Resp.getAge())
                        .setQueryType(Collections.singletonList(apiTypeEnums.getApiEnum().getApiKey()));
            }catch (Throwable e){
                // 回退扣费
                deductionFeeReturn(apiTypeEnums, userId, deptId);
                if (e instanceof ServiceException)
                    throw e;

                log.error("调用二要素校验接口失败", e);
                throw exception(DATA_QUERY_REPORT_ERROR);
            }
        }

        // 查询真假财务数据
        getRiskType(reqVO.getName(), reqVO.getIdCard(), dataQueryDO);

        // 创建用户授权书
        byte[] sqBookBytes = SqBookUtil.generateTagPng(reqVO.getName(), reqVO.getIdCard(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        String sqBookUrl = fileApi.createFile(sqBookBytes);
        dataQueryDO.setSqUrl(sqBookUrl);

        // 插入数据查询记录
        dataQueryMapper.insert(dataQueryDO);
        Long dataId = dataQueryDO.getId();

        // 记录成功的数量
        int successCount = 0;

        for (String queryType : queryTypes) {
            try {
                DataQueryRefreshReqVO refreshReqVO = new DataQueryRefreshReqVO();
                refreshReqVO.setDataId(dataId).setType(queryType).setQueryName(queryName).setQueryIdCard(queryIdCard).setQueryMobile(queryMobile);
                refreshData(refreshReqVO);
                successCount++;
            }catch (Throwable e){
                log.error("查询【{}】报告失败", queryType, e);
            }
        }

        return dataId;
    }

    @Override
    public void updateDataQuery(DataQuerySaveReqVO updateReqVO) {
        // 更新
        DataQueryDO updateObj = BeanUtils.toBean(updateReqVO, DataQueryDO.class);
        dataQueryMapper.updateById(updateObj);
    }

    @Override
    public void deleteDataQuery(Long id) {
        // 校验存在
        validateDataQueryExists(id);
        // 删除
        dataQueryMapper.deleteById(id);
        // 删除探针数据
        tanzcMapper.delete(DataQueryTanzcDO::getDataId, id);
    }

    @Override
    public void deleteDataQueryAll() {
        dataQueryMapper.delete(Wrappers.emptyWrapper());
    }

    private DataQueryDO validateDataQueryExists(Long id) {
        DataQueryDO dataQueryDO = dataQueryMapper.selectById(id);
        if (dataQueryDO == null) {
            throw exception(DATA_QUERY_NOT_EXISTS);
        }
        return dataQueryDO;
    }

    @Override
    public DataQueryRespVO getDataQuery(Long id) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        DataQueryRespVO respVO = BeanUtils.toBean(dataQueryMapper.selectById(id), DataQueryRespVO.class);
        if (respVO != null) {
            respVO.setQueryName(HideUtil.name(respVO.getQueryName()))
                    .setQueryIdCard(HideUtil.idCard(respVO.getQueryIdCard()))
                    .setQueryMobile(HideUtil.mobile(respVO.getQueryName()));

            respVO.setTanzc(tanzcMapper.selectOne(DataQueryTanzcDO::getDataId, id, DataQueryTanzcDO::getUserId, userId));
            respVO.setQjld(qjldMapper.selectOne(DataQueryQjldDO::getDataId, id, DataQueryQjldDO::getUserId, userId));
            respVO.setQjda(qjdaMapper.selectOne(DataQueryQjdaDO::getDataId, id, DataQueryQjdaDO::getUserId, userId));
            respVO.setFyfx(fyxqMapper.selectOne(DataQueryFyxqDO::getDataId, id, DataQueryFyxqDO::getUserId, userId));
            respVO.setZwsc(zwscMapper.selectOne(DataQueryZwscDO::getDataId, id, DataQueryZwscDO::getUserId, userId));
            respVO.setLsbg(lsbgMapper.selectOne(DataQueryLsbgDO::getDataId, id, DataQueryLsbgDO::getUserId, userId));
            respVO.setWdgz(wdgzMapper.selectOne(DataQueryWdgzDO::getDataId, id, DataQueryWdgzDO::getUserId, userId));
            respVO.setFqz(fqzMapper.selectOne(DataQueryFqzDO::getDataId, id, DataQueryFqzDO::getUserId, userId));
            respVO.setXfhx(xfhxMapper.selectOne(DataQueryXfhxDO::getDataId, id, DataQueryXfhxDO::getUserId, userId));
            respVO.setDtjd(dtjdMapper.selectOne(DataQueryDtjdDO::getDataId, id, DataQueryDtjdDO::getUserId, userId));
        }
        return respVO;
    }

    @Override
    public PageResult<DataQueryDO> getDataQueryPage(DataQueryPageReqVO pageReqVO) {
        return dataQueryMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dataQueryAuditAddBlacklist(Long id, String remark) {
        DataQueryDO dataQueryDO = validateDataQueryExists(id);

        // 判断状态是否已经加入过黑名单
        Boolean auditIsBlacklist = dataQueryDO.getAuditIsBlacklist();
        if (!auditIsBlacklist) {

            // 查询这个当前是否已经在财务数据里存在
            List<TfFinanceDO> tfFinances = tfFinanceMapper.selectList(Wrappers.<TfFinanceDO>lambdaQuery()
                    .eq(TfFinanceDO::getName, dataQueryDO.getQueryName())
                    .eq(TfFinanceDO::getIdCard, dataQueryDO.getQueryIdCard()));

            if (CollUtil.isEmpty(tfFinances)) {
                // 插入一条撸子记录
                TfFinanceDO tfFinanceDO = new TfFinanceDO();
                tfFinanceMapper.insert(tfFinanceDO
                        .setName(dataQueryDO.getQueryName())
                        .setMobile(dataQueryDO.getQueryMobile())
                        .setIdCard(dataQueryDO.getQueryIdCard())
                        .setType("撸子")
                        .setRiskType(2)
                        .setRecordTime(LocalDateTime.now())
                        .setRemark(remark));
                tfFinances.add(tfFinanceDO);
            } else {
                // 过滤出所有非撸子，并设置为撸子
                tfFinances.stream().filter(t -> !t.getRiskType().equals(2)).forEach(t -> {
                    tfFinanceMapper.update(TfFinanceDO::getId, t.getId(), TfFinanceDO::getRiskType, 2, TfFinanceDO::getRemark, remark);
                });
            }

            // 更新数据查询状态为已加入黑名单
            dataQueryMapper.update(DataQueryDO::getId, id, DataQueryDO::getAuditIsBlacklist, 1);

            // 更新所有数据查询记录里的风险信息为撸子
            DataQueryDO dataQuery = new DataQueryDO();
            dataQuery.setRiskType(2).setRiskTypeFinanceIds(tfFinances.stream().map(TfFinanceDO::getId).collect(Collectors.toList()));
            dataQueryMapper.update(dataQuery, Wrappers.<DataQueryDO>lambdaUpdate()
                    .eq(DataQueryDO::getQueryIdCard, dataQueryDO.getQueryIdCard())
                    .eq(DataQueryDO::getQueryName, dataQueryDO.getQueryName()));
        }
    }

    @Override
    //@Transactional
    public DataQuerySaveAuditRespVO createDataQueryAudit(String content, Long userId, Long deptId) {
        UserThreeInfoReqVO reqVO = analysisContent(content);

        // 扣除 二要素校验费用
        getApiPriceAndDeduction(TYPE_SF_2E_AUTH, userId, deptId);

        try {
            //  扣除 探针C的费用
            getApiPriceAndDeduction(TYPE_TZ_C, userId, deptId);
        } catch (ServiceException se) {
            // 若报错，则回退 二要素校验费用
            deductionFeeReturn(TYPE_SF_2E_AUTH, userId, deptId);
            throw se;
        }

        try {
            DataQuerySaveAuditRespVO respVO = new DataQuerySaveAuditRespVO();
            // 二要素认证
            DataQueryDO dataQueryDO = auditValidate(reqVO, userId, deptId, content);
            // 探针C
            DataQueryTanzcDO dataQueryTanzcDO = queryTzc(reqVO, userId, deptId, dataQueryDO.getId());

            respVO.setDataQueryDO(dataQueryDO).setDataQueryTanzcDO(dataQueryTanzcDO);
            return respVO;
        } catch (Throwable e) {
            log.error("智能审核失败：", e);
            // 回退金额
            deductionFeeReturn(TYPE_SF_2E_AUTH, userId, deptId);
            deductionFeeReturn(TYPE_TZ_C, userId, deptId);
            throw exception(DATA_QUERY_AUDIT_ERROR);
        }
    }

    public UserThreeInfoReqVO analysisContent(String content) {
        UserThreeInfoReqVO reqVO = new UserThreeInfoReqVO();

        String[] contentLineArr = content.split("\n");
        for (String contentLine : contentLineArr) {
            if (StrUtil.isNotBlank(contentLine)) {
                String[] contentArr = contentLine.split("：");
                String valStr = contentArr.length == 2 ? contentArr[1].trim() : "";

                if (contentLine.contains("姓名"))
                    reqVO.setName(valStr);
                else if (contentLine.contains("身份证号") || contentLine.contains("身份证"))
                    reqVO.setIdCard(valStr);
                else if (contentLine.contains("手机号") || contentLine.contains("联系方式") || contentLine.contains("联系电话"))
                    reqVO.setPhone(valStr);
            }
        }

        if (StrUtil.isBlank(reqVO.getName()) || StrUtil.isBlank(reqVO.getIdCard()))
            throw exception(INFO_COMPARISON_CONTENT_ANALYSIS_FAIL);

        return reqVO;
    }

    /**
     * 基本信息认证（二/三要素验证）
     */
    private DataQueryDO auditValidate(UserThreeInfoReqVO reqVO, Long userId, Long deptId, String content) {
        UserThreeInfoReqVO newReqVO = new UserThreeInfoReqVO();
        newReqVO.setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());
        // 二要素认证
        ZCI001RespVO auth2Resp = backInvestApi.authTwoE(newReqVO);

        DataQueryDO dataQueryDO = new DataQueryDO();

        // 查询真假财务数据
        getRiskType(reqVO.getName(), reqVO.getIdCard(), dataQueryDO);

        // 构建查询数据
        dataQueryDO.setUserId(userId).setDeptId(deptId)
                .setValidMethod(1).setQueryName(reqVO.getName()).setQueryIdCard(reqVO.getIdCard()).setQueryMobile(reqVO.getPhone())
                .setQueryType(CollUtil.newArrayList(TYPE_SF_2E_AUTH.getApiEnum().getApiKey(), TYPE_TZ_C.getApiEnum().getApiKey()))
                .setQueryTime(LocalDateTime.now())
                .setVaildResult("0".equals(auth2Resp.getFinal_auth_result()) ? 1 : 2)
                .setValidBirthday(auth2Resp.getBirthday())
                .setValidAddress(auth2Resp.getAddress())
                //.setValidAddressType()
                .setValidConstellation(auth2Resp.getConstellation())
                .setValidGender(auth2Resp.getGender())
                .setValidAge(auth2Resp.getAge())
                .setIsAudit(true)
                .setAutidContent(content);
        // 插入数据
        dataQueryMapper.insert(dataQueryDO);
        return dataQueryDO;
    }

    private void getRiskType(String name, String idCard, DataQueryDO dataQueryDO){
        // 查询真假财务数据
        List<TfFinanceDO> tfFinances = tfFinanceMapper.selectList(Wrappers.<TfFinanceDO>lambdaQuery()
                .eq(TfFinanceDO::getName, name));

        int riskType;
        List<Long> riskTypeFinanceIds = new ArrayList<>();

        if (CollUtil.isEmpty(tfFinances)) {
            riskType = 1;
            riskTypeFinanceIds = new ArrayList<>();
        } else {
            // 判断是否有身份证号相等的
            List<TfFinanceDO> nowUserFinances = tfFinances
                    .stream()
                    .filter(o -> StrUtil.isNotBlank(o.getIdCard()) && o.getIdCard().equals(idCard))
                    .collect(Collectors.toList());
            // 若有身份证号一样的，则判断当前财务状态
            if (CollUtil.isNotEmpty(nowUserFinances)) {
                if (nowUserFinances.stream().anyMatch(f -> f.getRiskType() == 2)) {
                    riskType = 2;
                    riskTypeFinanceIds = nowUserFinances.stream().filter(f -> f.getRiskType() == 2).map(TfFinanceDO::getId).collect(Collectors.toList());
                } else
                    riskType = 1;
            } else {
                riskType = 3;
                riskTypeFinanceIds = tfFinances.stream().map(TfFinanceDO::getId).collect(Collectors.toList());
            }
        }

        dataQueryDO.setRiskType(riskType).setRiskTypeFinanceIds(riskTypeFinanceIds);
    }

    /**
     * 探针C查询
     */
    private DataQueryTanzcDO queryTzc(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        UserThreeInfoReqVO newReqVO = new UserThreeInfoReqVO();
        newReqVO.setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());

        ZCI023RespVO zci023RespVO = backInvestApi.tzC(newReqVO);
        if (zci023RespVO == null)
            zci023RespVO = new ZCI023RespVO().setResult_code("4");
        String resultCode = zci023RespVO.getResult_code();

        DataQueryTanzcDO dataQueryTanzcDO = new DataQueryTanzcDO();
        dataQueryTanzcDO.setUserId(userId).setDeptId(deptId).setDataId(dataId)
                .setResultCode("2".equals(resultCode) ? "2" : ("4".equals(resultCode) ? "4" : "1"))
                .setMaxOverdueAmt(zci023RespVO.getMax_overdue_amt())
                .setMaxOverdueDays(zci023RespVO.getMax_overdue_days())
                .setLatestOverdueTime(zci023RespVO.getLatest_overdue_time())
                .setMaxPerformanceAmt(zci023RespVO.getMax_performance_amt())
                .setLatestPerformanceTime(zci023RespVO.getLatest_performance_time())
                .setCountPerformance(zci023RespVO.getCount_performance())
                .setCurrentlyOverdue(zci023RespVO.getCurrently_overdue())
                .setCurrentlyPerformance(zci023RespVO.getCurrently_performance())
                .setAccExc(zci023RespVO.getAcc_exc())
                .setAccSleep(zci023RespVO.getAcc_sleep())
                .setQueryTime(LocalDateTime.now());

        // 查询是否存在
        DataQueryTanzcDO dbOld = tanzcMapper.selectOne(DataQueryTanzcDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            tanzcMapper.insert(dataQueryTanzcDO);
        else
            tanzcMapper.updateById(dataQueryTanzcDO.setId(dbOld.getId()));

        return dataQueryTanzcDO;
    }

    /**
     * 全景雷达
     */
    private DataQueryQjldDO queryQjld(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        UserThreeInfoReqVO newReqVO = new UserThreeInfoReqVO();
        newReqVO.setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());

        ZCI008RespVO zci008RespVO = backInvestApi.qjld(newReqVO);
        DataQueryQjldDO dataQueryQjldDO;
        if (zci008RespVO != null)
            dataQueryQjldDO = ObjConvertUtil.convertQjld(zci008RespVO);
        else
            dataQueryQjldDO = new DataQueryQjldDO();

        dataQueryQjldDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now());

        // 查询是否存在
        DataQueryQjldDO dbOld = qjldMapper.selectOne(DataQueryQjldDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            qjldMapper.insert(dataQueryQjldDO);
        else
            qjldMapper.updateById(dataQueryQjldDO.setId(dbOld.getId()));

        return dataQueryQjldDO;
    }

    /**
     * 全景档案
     */
    private DataQueryQjdaDO queryQjda(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        /*UserThreeInfoReqVO newReqVO1 = new UserThreeInfoReqVO();
        newReqVO1.setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());*/
        // 无需请求本体，本体的数据无用
        //ZCI022RespVO qjdan = backInvestApi.qjdan(newReqVO1);

        // 请求借选指数
        UserThreeInfoReqVO newReqVO2 = new UserThreeInfoReqVO();
        newReqVO2.setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());
        ZCI021RespVO jxzs = backInvestApi.jxzs(newReqVO2);

        //DataQueryQjdaDO dataQueryQjdaDO = ObjConvertUtil.convertQjda(qjdan);
        DataQueryQjdaDO dataQueryQjdaDO = new DataQueryQjdaDO();
        dataQueryQjdaDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now())
                .setJxzs(jxzs);

        // 查询是否存在
        DataQueryQjdaDO dbOld = qjdaMapper.selectOne(DataQueryQjdaDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            qjdaMapper.insert(dataQueryQjdaDO);
        else
            qjdaMapper.updateById(dataQueryQjdaDO.setId(dbOld.getId()));

        return dataQueryQjdaDO;
    }

    /**
     * 法院风险
     */
    private DataQueryFyxqDO queryFyfx(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        UserThreeInfoReqVO newReqVO = new UserThreeInfoReqVO();
        newReqVO.setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());
        List<ZCI007RespVO> fyfxList = backInvestApi.fyfx(newReqVO);

        DataQueryFyxqDO dataQueryFyxqDO;
        if (CollUtil.isNotEmpty(fyfxList)) {
            dataQueryFyxqDO = ObjConvertUtil.convertFyfx(fyfxList, reqVO.getName(), reqVO.getIdCard());
        }else
            dataQueryFyxqDO = new DataQueryFyxqDO();

        dataQueryFyxqDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now());

        // 查询是否存在
        DataQueryFyxqDO dbOld = fyxqMapper.selectOne(DataQueryFyxqDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            fyxqMapper.insert(dataQueryFyxqDO);
        else
            fyxqMapper.updateById(dataQueryFyxqDO.setId(dbOld.getId()));

        return dataQueryFyxqDO;
    }

    /**
     * 在网时长
     */
    private DataQueryZwscDO queryZwsc(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        ZCI003RespVO sjzwsc = backInvestApi.sjzwsc(new ZCI003ReqVO().setPhone(reqVO.getPhone()));

        DataQueryZwscDO dataQueryZwscDO = new DataQueryZwscDO();
        dataQueryZwscDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now())
                .setInTime(sjzwsc.getInTime()).setOperators(sjzwsc.getOperators());

        // 查询是否存在
        DataQueryZwscDO dbOld = zwscMapper.selectOne(DataQueryZwscDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            zwscMapper.insert(dataQueryZwscDO);
        else
            zwscMapper.updateById(dataQueryZwscDO.setId(dbOld.getId()));

        return dataQueryZwscDO;
    }

    /**
     * 流水报告
     */
    private DataQueryLsbgDO queryLsbg(UserThreeInfoReqVO userThreeInfoReqVO, Long userId, Long deptId, Long dataId) {
        String lsbgUrl = backInvestApi.lsbg(userThreeInfoReqVO.getIdCard());

        DataQueryLsbgDO dataQueryLsbgDO = new DataQueryLsbgDO();
        dataQueryLsbgDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now())
                .setQueryName(userThreeInfoReqVO.getName()).setQueryIdCard(userThreeInfoReqVO.getIdCard())
                .setUrl(lsbgUrl);

        // 查询是否存在
        DataQueryLsbgDO dbOld = lsbgMapper.selectOne(DataQueryLsbgDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            lsbgMapper.insert(dataQueryLsbgDO);
        else
            lsbgMapper.updateById(dataQueryLsbgDO.setId(dbOld.getId()));

        return dataQueryLsbgDO;
    }

    /**
     * 司法报告
     */
    private DataQueryWdgzDO queryWdgz(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        // 获取授权书
        String sqBookUrl = null;
        DataQueryDO dataQueryDO = dataQueryMapper.selectById(dataId);
        if (dataQueryDO != null){
            sqBookUrl = dataQueryDO.getSqUrl();
        }
        if (StrUtil.isBlank(sqBookUrl)){
            byte[] sqBookBytes = SqBookUtil.generateTagPng(reqVO.getName(), reqVO.getIdCard(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            sqBookUrl = fileApi.createFile(sqBookBytes);

            // 更新授权书
            dataQueryMapper.update(DataQueryDO::getId, dataId, DataQueryDO::getSqUrl, sqBookUrl);
        }

        ZCI101ReqVO newReqVO = new ZCI101ReqVO();
        newReqVO.setAccessoryUrl(sqBookUrl)
                .setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());
        // 司法报告 接口调用
        ZCI101RespVO sfbg = backInvestApi.sfbg(newReqVO);

        DataQueryWdgzDO dataQueryWdgzDO = BeanUtils.toBean(sfbg, DataQueryWdgzDO.class);
        dataQueryWdgzDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now());

        // 查询是否存在
        DataQueryWdgzDO dbOld = wdgzMapper.selectOne(DataQueryWdgzDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            wdgzMapper.insert(dataQueryWdgzDO);
        else
            wdgzMapper.updateById(dataQueryWdgzDO.setId(dbOld.getId()));

        return dataQueryWdgzDO;
    }

    /**
     * 逾期探查报告
     */
    private DataQueryFqzDO queryFqz(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        // 获取授权书
        String sqBookUrl = null;
        DataQueryDO dataQueryDO = dataQueryMapper.selectById(dataId);
        if (dataQueryDO != null){
            sqBookUrl = dataQueryDO.getSqUrl();
        }
        if (StrUtil.isBlank(sqBookUrl)){
            byte[] sqBookBytes = SqBookUtil.generateTagPng(reqVO.getName(), reqVO.getIdCard(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            sqBookUrl = fileApi.createFile(sqBookBytes);

            // 更新授权书
            dataQueryMapper.update(DataQueryDO::getId, dataId, DataQueryDO::getSqUrl, sqBookUrl);
        }

        ZCI101ReqVO newReqVO = new ZCI101ReqVO();
        newReqVO.setAccessoryUrl(sqBookUrl)
                .setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());
        // 逾期探查报告 接口调用
        ZCI105RespVO yqtzbg = backInvestApi.yqtzbg(newReqVO);

        DataQueryFqzDO dataQueryFqzDO = BeanUtils.toBean(yqtzbg, DataQueryFqzDO.class);
        dataQueryFqzDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now());

        // 查询是否存在
        DataQueryFqzDO dbOld = fqzMapper.selectOne(DataQueryFqzDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            fqzMapper.insert(dataQueryFqzDO);
        else
            fqzMapper.updateById(dataQueryFqzDO.setId(dbOld.getId()));

        return dataQueryFqzDO;
    }

    /**
     * 智查全景报告
     */
    private DataQueryXfhxDO queryXfhx(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        // 获取授权书
        String sqBookUrl = null;
        DataQueryDO dataQueryDO = dataQueryMapper.selectById(dataId);
        if (dataQueryDO != null){
            sqBookUrl = dataQueryDO.getSqUrl();
        }
        if (StrUtil.isBlank(sqBookUrl)){
            byte[] sqBookBytes = SqBookUtil.generateTagPng(reqVO.getName(), reqVO.getIdCard(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            sqBookUrl = fileApi.createFile(sqBookBytes);

            // 更新授权书
            dataQueryMapper.update(DataQueryDO::getId, dataId, DataQueryDO::getSqUrl, sqBookUrl);
        }

        ZCI101ReqVO newReqVO = new ZCI101ReqVO();
        newReqVO.setAccessoryUrl(sqBookUrl)
                .setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());
        // 智查全景报告 接口调用
        ZCI104RespVO zcqjbg = backInvestApi.zcqjbg(newReqVO);

        DataQueryXfhxDO dataQueryXfhxDO = BeanUtils.toBean(zcqjbg, DataQueryXfhxDO.class);
        dataQueryXfhxDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now());

        // 查询是否存在
        DataQueryXfhxDO dbOld = xfhxMapper.selectOne(DataQueryXfhxDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            xfhxMapper.insert(dataQueryXfhxDO);
        else
            xfhxMapper.updateById(dataQueryXfhxDO.setId(dbOld.getId()));

        return dataQueryXfhxDO;
    }

    /**
     * TC报告
     */
    private DataQueryDtjdDO queryDtjd(UserThreeInfoReqVO reqVO, Long userId, Long deptId, Long dataId) {
        // 获取授权书
        String sqBookUrl = null;
        DataQueryDO dataQueryDO = dataQueryMapper.selectById(dataId);
        if (dataQueryDO != null){
            sqBookUrl = dataQueryDO.getSqUrl();
        }
        if (StrUtil.isBlank(sqBookUrl)){
            byte[] sqBookBytes = SqBookUtil.generateTagPng(reqVO.getName(), reqVO.getIdCard(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            sqBookUrl = fileApi.createFile(sqBookBytes);

            // 更新授权书
            dataQueryMapper.update(DataQueryDO::getId, dataId, DataQueryDO::getSqUrl, sqBookUrl);
        }

        ZCI101ReqVO newReqVO = new ZCI101ReqVO();
        newReqVO.setAccessoryUrl(sqBookUrl)
                .setPhone(reqVO.getPhone()).setName(reqVO.getName()).setIdCard(reqVO.getIdCard());
        // TC报告 接口调用
        ZCI106RespVO tcbg = backInvestApi.tcbg(newReqVO);

        DataQueryDtjdDO dataQueryDtjdDO = BeanUtils.toBean(tcbg, DataQueryDtjdDO.class);
        dataQueryDtjdDO.setUserId(userId).setDeptId(deptId).setDataId(dataId).setQueryTime(LocalDateTime.now());

        // 查询是否存在
        DataQueryDtjdDO dbOld = dtjdMapper.selectOne(DataQueryDtjdDO::getDataId, dataId);
        if (Objects.isNull(dbOld))
            dtjdMapper.insert(dataQueryDtjdDO);
        else
            dtjdMapper.updateById(dataQueryDtjdDO.setId(dbOld.getId()));

        return dataQueryDtjdDO;
    }

    private void getApiPriceAndDeduction(ApiTypeEnums apiTypeEnums, Long userId, Long deptId) {
        try {
            // 获取价格
            ApiTypeInfoDO auth2Api = apiTypeInfoService.getApiPriceByType(apiTypeEnums);
            // 扣费
            UserExtendSaveReqVO userExtendSaveReqVO = new UserExtendSaveReqVO();
            userExtendSaveReqVO.setUserId(userId).setDeptId(deptId)
                    .setType(false).setAmount(auth2Api.getPrice())
                    .setTitle(auth2Api.getName());
            userExtendService.updateUserBalance(userExtendSaveReqVO);
        } catch (Throwable e) {
            // 回退扣费金额
            deductionFeeReturn(apiTypeEnums, userId, deptId);

            if (e instanceof ServiceException)
                throw e;

            log.error("费用扣除失败：", e);

            throw exception(USER_BALANCE_DEDUCTION_ERROR);
        }
    }

    private void deductionFeeReturn(ApiTypeEnums apiTypeEnums, Long userId, Long deptId) {
        // 获取价格
        ApiTypeInfoDO auth2Api = apiTypeInfoService.getApiPriceByType(apiTypeEnums);
        // 扣费
        UserExtendSaveReqVO userExtendSaveReqVO = new UserExtendSaveReqVO();
        userExtendSaveReqVO.setUserId(userId).setDeptId(deptId)
                .setType(true).setAmount(auth2Api.getPrice())
                .setTitle(auth2Api.getName() + " 扣费退回");
        userExtendService.updateUserBalance(userExtendSaveReqVO);
    }

    @Override
    public PageResult<DataQueryAuditSimpleRespVO> getDataQueryPageAudit(DataQueryPageReqVO pageReqVO) {
        return dataQueryMapper.getDataQueryPageAudit(pageReqVO);
    }

    @Override
    public DataQuerySaveAuditRespVO getDataQueryAudit(Long id) {
        DataQuerySaveAuditRespVO respVO = new DataQuerySaveAuditRespVO();

        DataQueryDO dataQueryDO = dataQueryMapper.selectById(id);
        if (dataQueryDO != null){
            dataQueryDO.setQueryName(HideUtil.name(dataQueryDO.getQueryName()))
                    .setQueryIdCard(HideUtil.idCard(dataQueryDO.getQueryIdCard()))
                    .setQueryMobile(HideUtil.mobile(dataQueryDO.getQueryName()));
        }
        respVO.setDataQueryDO(dataQueryDO).setDataQueryTanzcDO(tanzcMapper.selectOne(DataQueryTanzcDO::getDataId, id));

        return respVO;
    }

    @Override
    public Long createAuditDataQuery(DataQueryAuditSaveReqVO auditSaveReqVO, Long userId, Long deptId) {
        Long dataId = auditSaveReqVO.getId();
        List<String> queryTypes = auditSaveReqVO.getQueryType();

        // 查询数据查询记录
        DataQueryDO dataQueryDO = dataQueryMapper.selectById(dataId);
        if (Objects.isNull(dataQueryDO))
            throw exception(DATA_QUERY_NOT_EXISTS);

        // 记录成功的数量
        int successCount = 0;

        for (String queryType : queryTypes) {
            try {
                DataQueryRefreshReqVO refreshReqVO = new DataQueryRefreshReqVO();
                refreshReqVO.setDataId(dataId).setType(queryType)
                        .setQueryName(dataQueryDO.getQueryName()).setQueryIdCard(dataQueryDO.getQueryIdCard())
                        .setQueryMobile(dataQueryDO.getQueryMobile());
                refreshData(refreshReqVO);
                successCount++;
            }catch (Throwable e){
                log.error("查询【{}】报告失败", queryType, e);
            }
        }

        return dataId;
    }
}